package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.appkit.ConfigKit;
import com.firefightingiot.firefightingiot.model.*;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.DayUtil;
import com.firefightingiot.firefightingiot.support.utils.MyLogger;
import com.firefightingiot.firefightingiot.support.utils.WebUtil;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

//import org.bytedeco.javacpp.opencv_core;
//import org.bytedeco.javacv.*;

@Service
@Slf4j
public class UploadFileService extends BaseService {

    @Resource
    public MyLogger logger;

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private DeviceAlarmLogMapper deviceAlarmLogMapper;
    @Resource
    private DeviceAlarmLogImgMapper deviceAlarmLogImgMapper;
    @Resource
    private FireService fireService;
    @Resource
    private UseDictMapper useDictMapper;
    @Resource
    private DeviceTypeMapper deviceTypeMapper;
    @Resource
    RegionMapper regionMapper;
    @Resource
    IpSoundFileNameMapper ipSoundFileNameMapper;
    @Resource
    LedUploadFileMapper ledUploadFileMapper;
    @Resource
    ChainofcvidenceUploadFileMapper chainofcvidenceUploadFileMapper;

    /**
     * @param params
     * @return
     * @Title: getTemplte <br>
     * @Description: (下载模板) <br>
     * @author 石延杰<br>
     */

    public ResponseEntity<byte[]> getTemplte(Map<String, Object> params) throws Exception {
        JSONObject obj = new JSONObject();
        //模板list
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("序号", "");
        map.put("省份", "");
        map.put("市级", "");
        map.put("区县", "");
        map.put("街道", "");
        map.put("街道编号", "");
        map.put("机构名称", "");
        map.put("机构ID", "");
        map.put("单位名称", "");
        map.put("单位ID", "");
        map.put("设备类型编号", "");
        map.put("设备分类编号", "");
        map.put("安装位置", "");
        map.put("设备编号", "");
        map.put("联系人", "");
        map.put("电话1", "");
        map.put("电话2", "");
        map.put("安装人员", "");
        map.put("安装时间", "");
        Iterable<?> rowData = map.keySet();
        fieldList.add(map);
        //机构list
        List<Map<String, String>> orgList = new ArrayList<>();
        Map<String, String> orgmap = new LinkedHashMap<>();
        orgmap.put("机构名称", "");
        orgmap.put("机构Id", "");
        orgList.add(orgmap);
        List<Map<String, String>> dataList = (List<Map<String, String>>) makeDataForJSON(obj, "systemsetup", "config", "getOrgList", "systemsetup");
        orgList.addAll(dataList);
        //行政区划
        List<Map<String, String>> regionList = new ArrayList<>();
        Map<String, String> regionmap = new LinkedHashMap<>();
        regionmap.put("行政区划上级名称", "");
        regionmap.put("行政区划上级ID", "");
        regionmap.put("行政区划名称", "");
        regionmap.put("行政区划ID", "");
        regionList.add(regionmap);
        List<Map<String, String>> dataRegionList = (List<Map<String, String>>) makeDataForJSON(obj, "businessJava", "config", "getGegionList", "business");
        regionList.addAll(dataRegionList);
        //单位list
        List<Map<String, String>> businessList = new ArrayList<>();
        Map<String, String> businessMap = new LinkedHashMap<>();
        businessMap.put("行政区划ID", "");
        businessMap.put("行政区划名称", "");
        businessMap.put("单位名称", "");
        businessMap.put("单位ID", "");
        businessList.add(businessMap);
        List<Map<String, String>> dataBusinessList = (List<Map<String, String>>) makeDataForJSON(obj, "businessJava", "config", "getBusiness", "business");
        businessList.addAll(dataBusinessList);
        //设备类型
        List<Map<String, String>> deviceTypeList = new ArrayList<>();
        Map<String, String> deviceTypeMap = new LinkedHashMap<>();
        deviceTypeMap.put("设备类型名称", "");
        deviceTypeMap.put("设备类型编号", "");
        deviceTypeMap.put("设备分类编号", "");
        deviceTypeList.add(deviceTypeMap);
        List<DeviceType> deviceList = deviceTypeMapper.selectList(new QueryWrapper<DeviceType>());
        List<Map<String, String>> datadeviceTypeList = new ArrayList<>();
        for (DeviceType deviceType : deviceList) {
            Map<String, String> deviceMap = new HashMap<>();
            deviceMap.put("id", deviceType.getId());
            deviceMap.put("name", deviceType.getName());
            deviceMap.put("type", deviceType.getType());
            datadeviceTypeList.add(deviceMap);
        }
        deviceTypeList.addAll(datadeviceTypeList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String code = UUID.randomUUID().toString();
        String webPath = "";
        String fileName = "import_part(" + "数据导入" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        webPath = url.toString().replace("/getTemplte", "/downloadExcel?fileName=" + fileName);
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.merge(8, "注释：\r\n1.必填项:街道编号、机构名称、机构ID、单位名称、单位ID、设备分类、设备分类编号、设备编号；\r\n" +
                "2.街道编号数据来源:见工作表行政区划；\r\n" +
                "3.已有单位的机构ID、机构名称、单位名称、单位ID数据来源:见工作表单位列表;\r\n" +
                "4.新单位的机构ID、机构名称数据来源:见工作表机构;\r\n" +
                "5.设备分类、设备分类编号数据来源:见工作表设备类型;\r\n" +
                "6.设备分类:1 电气火灾 2 消防用水 3 烟感 4 可燃气体 5 火灾自动联网 6 消防可视化;\r\n", false);
        writer.setRowHeight(0, 110);
        writer.setColumnWidth(0, 20);
        writer.setColumnWidth(1, 25);
        writer.setColumnWidth(2, 25);
        writer.setColumnWidth(3, 25);
        writer.setColumnWidth(4, 25);
        writer.setColumnWidth(5, 25);
        writer.setColumnWidth(6, 30);
        writer.setColumnWidth(7, 40);
        writer.setColumnWidth(8, 40);
        writer.setColumnWidth(9, 40);
        writer.setColumnWidth(10, 35);
        writer.setColumnWidth(11, 20);
        writer.setColumnWidth(12, 40);
        writer.setColumnWidth(13, 30);
        writer.setColumnWidth(14, 25);
        writer.setColumnWidth(15, 35);
        writer.setColumnWidth(16, 35);
        writer.setColumnWidth(17, 25);
        writer.setColumnWidth(18, 25);
        CellStyle cellStyle = writer.getOrCreateCellStyle(0, 0);
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setWrapText(true);
        Font font = writer.createFont();
        font.setColor(Font.COLOR_RED);
        cellStyle.setFont(font);
        writer.setCurrentRow(1);
        writer = writer.writeHeadRow(rowData);
        writer.setOnlyAlias(false);
        writer.renameSheet("导入");
        writer.flush();
        writer.setSheet("机构");
        font.setColor(Font.COLOR_NORMAL);
        writer.setCurrentRow(0);
        writer.write(orgList);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 40);
        writer.setSheet("行政区划");
        writer.setCurrentRow(0);
        writer.write(regionList);
        writer.setColumnWidth(0, 45);
        writer.setColumnWidth(1, 40);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setSheet("单位列表");
        writer.setCurrentRow(0);
        writer.write(businessList);
        writer.setColumnWidth(0, 40);
        writer.setColumnWidth(1, 45);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 40);
        writer.setSheet("设备类型");
        writer.setCurrentRow(0);
        writer.write(deviceTypeList);
        writer.setColumnWidth(0, 20);
        writer.setColumnWidth(1, 20);
        writer.setColumnWidth(2, 20);
        // 关闭writer，释放内存
        writer.close();
        //返回二进制流
        return downloadExcel(fileName);
    }
    /**
     * @Author YangYu
     * @Description 设备导入模板下载
     * @Date Created in 9:50 2022/9/13
     * @Param [params]
     */

    public ResponseEntity<byte[]> getTemplate(Map<String, Object> params) throws Exception {
        //模板list
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("设备名称", "");
        map.put("设备编号", "");
        map.put("物联网卡号", "");
        map.put("传输装置编码", "");
        map.put("安装位置", "");
        Iterable<?> rowData = map.keySet();
        fieldList.add(map);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String fileName = "import_part(" + "数据导入" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.merge(4, "注释：\r\n必填项:设备名称、设备编号、安装位置", false);
        writer.setRowHeight(0, 30);
        writer.setColumnWidth(0, 20);
        writer.setColumnWidth(1, 25);
        writer.setColumnWidth(2, 25);
        writer.setColumnWidth(3, 25);
        writer.setColumnWidth(4, 30);
        CellStyle cellStyle = writer.getOrCreateCellStyle(0, 0);
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setWrapText(true);
        Font font = writer.createFont();
        font.setColor(Font.COLOR_RED);
        cellStyle.setFont(font);
        writer.setCurrentRow(1);
        writer = writer.writeHeadRow(rowData);
        writer.setOnlyAlias(false);
        writer.renameSheet("导入");
        writer.flush();
        // 关闭writer，释放内存
        writer.close();
        //返回二进制流
        return downloadExcel(fileName);
    }
    /**
     * @param
     * @return
     * @Title: addUpload <br>
     * @Description: (上传) <br>
     * @author 石延杰<br>
     */
    public RespEntity addUpload(Map<String, Object> dict) throws Exception {
        //处理支持form-data和json两种方式
        JSONObject params = new JSONObject();
        String webPath = "";
        Map<String, String> map = new LinkedHashMap<>();//组装excel表应该有的列名
        map.put("序号", "");
        map.put("省份", "");
        map.put("市级", "");
        map.put("区县", "");
        map.put("街道", "");
        map.put("街道编号", "");
        map.put("机构名称", "");
        map.put("机构ID", "");
        map.put("单位名称", "");
        map.put("单位ID", "");
        map.put("设备类型编号", "");
        map.put("设备分类编号", "");
        map.put("安装位置", "");
        map.put("设备编号", "");
        map.put("联系人", "");
        map.put("电话1", "");
        map.put("电话2", "");
        map.put("安装人员", "");
        map.put("安装时间", "");
        List<Map<String, Object>> excelList = (List<Map<String, Object>>) dict.get("listData");//获取excel表中的数据
        List<Map<String, Object>> removeList = new ArrayList<>();//删除的list
        //rest请求行政区划集合
        //List<Region> regionList2 = regionMapper.selectList(new QueryWrapper<Region>());//rest!!!!!!!!
        JSONArray regionList = (JSONArray) makeDataForJSON(params, "businessJava", "config", "getGegionList", "business");
        Map<String, String> regionNameMap = new HashMap<>();//行政区划的映射：最底层行政区划：三级名称
        Map<String, String> regionPidMap = new HashMap<>();//行政区划的映射：最底层行政区划：所有级的id
        List<String> regionIdList = new ArrayList<>();//行政区划的id集合
        for (Object oo : regionList) {
            com.alibaba.fastjson.JSONObject region = (com.alibaba.fastjson.JSONObject) oo;
            regionNameMap.put(region.getString("id"), region.getString("allname"));
            regionPidMap.put(region.getString("id"), region.getString("allid"));
            regionIdList.add(region.getString("id"));
        }
        //rest调用系统设置模块
        Map<String, Object> getAllOrgId = restCheck(params, "systemsetup", "getAllOrgIdList", "systemsetup");
        //获取目前有的设备编号
        List<DeviceBusiness> deviceBusinessOldList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>());
        List<String> numberList = new ArrayList<>();
        for (DeviceBusiness d : deviceBusinessOldList) {
            numberList.add(d.getNumber());
        }
        //之后新增的设备
        List<String> numberExcelList = new ArrayList<>();
        //存储新增的单位
        Map<String, String> buMap = new HashMap<>();//单位名称：单位id
        //查询现在的单位id集合，之后新增了累加在上边
        List<String> allBuIdList = new ArrayList<>();
        //rest调用一企一档接口,获取所有单位id
        JSON json = makeDataForJSONForTokenMethod(params, "businessJava", "config", "getBusinessId", "business", "get");
        if (json instanceof com.alibaba.fastjson.JSONObject) {
            com.alibaba.fastjson.JSONObject checkaddrRecordListJsonN = (com.alibaba.fastjson.JSONObject) json;
            if (StrUtil.isNotBlank(checkaddrRecordListJsonN.getString("methodCodeFlag"))) {
                return RespEntity.expire();
            }
            return RespEntity.fail(((com.alibaba.fastjson.JSONObject) json).getString("msg"));
        } else {
            allBuIdList = (List<String>) json;
        }
        //存储新增的机构
        Map<String, String> orgMap = new HashMap<>();//机构名称：机构id
        //查询现在的机构id集合，之后新增了累加在上边
        List<String> allOrgIdList = new ArrayList<>();//rest!!!!!!!!
        JSON allOrgId = makeDataForJSONForTokenMethod(params, "systemsetup", "config", "getOrganizationListId", "systemsetup", "get");
        if (json instanceof com.alibaba.fastjson.JSONObject) {
            com.alibaba.fastjson.JSONObject checkaddrRecordListJsonN = (com.alibaba.fastjson.JSONObject) json;
            if (StrUtil.isNotBlank(checkaddrRecordListJsonN.getString("methodCodeFlag"))) {
                return RespEntity.expire();
            }
            return RespEntity.fail(((com.alibaba.fastjson.JSONObject) json).getString("msg"));
        } else {
            allOrgIdList = (List<String>) allOrgId;
        }
        //判断excel中的列名和应该有的列名是不是一致
        if (excelList != null && excelList.size() > 0) {
            Map<String, Object> excelMap = excelList.get(0);
            Set<String> set = excelMap.keySet();
            for (String s : set) {
                if (!map.containsKey(s)) {
                    return RespEntity.fail("文件表头不匹配");
                }
            }
        }
        List<LinkedHashMap<String, Object>> errorList = new ArrayList<>();//出错的list
        SqlSession session = getSqlSession();
        boolean errorFlag = true;
        try {
            DeviceBusinessMapper deviceMapper = getMapper(session, DeviceBusinessMapper.class);
            List<?> object = new ArrayList<>();
            BigData data = new BigData(excelList);
            for (int i = 0; i < data.getNum(); i++) {
                //boolean insertFlag = false;
                List<DeviceBusiness> insertDeviceList = new ArrayList<>();//存储一千条要保存的DeviceBusiness集合
                List<Business> insertBusinessList = new ArrayList<>();//存储一千条要保存的Business集合
                List<Organization> insertOrganizationList = new ArrayList<>();//存储一千条要保存的Organization集合
                List<Map<String, Object>> dataMapList = data.getData(i);//excel中一组数据
                List<String> classify = new ArrayList<>();
                classify.add("1");
                classify.add("2");
                classify.add("3");
                classify.add("4");
                classify.add("5");
                classify.add("6");
                classify.add("7");
                classify.add("8");
                classify.add("9");
                classify.add("10");
                List<String> type = new ArrayList<>();
                type.add("1");
                type.add("2");
                type.add("3");
                type.add("4");
                type.add("5");
                type.add("6");
                type.add("7");
                type.add("8");
                type.add("9");
                type.add("10");
                type.add("11");
                type.add("12");
                type.add("13");
                type.add("14");
                type.add("15");
                type.add("16");
                type.add("17");
                type.add("18");
                type.add("19");
                type.add("20");
                type.add("21");
                type.add("22");
                type.add("23");
                type.add("24");
                type.add("25");
                type.add("26");
                for (Map<String, Object> dataMap : dataMapList) {
                    Set<String> set = dataMap.keySet();
                    String error = "";//错误信息
                    String buId = "";//单位id
                    String orgId = "";//机构id
                    String buName = "";//单位名称
                    String orgName = "";//机构名称
                    String area = "";//街道编号
                    String number = "";//设备编号
                    String deviceClassify = "";//设备分类编号
                    String deviceType = "";//设备分类编号
                    String phone1 = "";//电话1
                    String phone2 = "";//电话2
                    for (String s : set) {
                        if (dataMap.get(s) == null) dataMap.put(s, "");//防止下载错误list的时候，为空时错行
                        System.out.println(s + "------------------" + dataMap.get(s).toString());
                        //为空时为不符合的数据
                        if (s.equals("街道编号") || s.equals("机构ID") || s.equals("单位名称") || s.equals("设备分类编号") || s.equals("设备编号") || s.equals("设备类型编号")) {//!!!!!!!
                            if (s.equals("设备编号")) number = dataMap.get(s).toString();
                            if (s.equals("单位名称")) buName = dataMap.get(s).toString();
                            if (s.equals("机构ID")) orgId = dataMap.get(s).toString();
                            if (s.equals("街道编号")) area = dataMap.get(s).toString();
                            if (s.equals("设备分类编号")) deviceClassify = dataMap.get(s).toString();
                            if (s.equals("设备类型编号")) deviceType = dataMap.get(s).toString();
                            String value = dataMap.get(s).toString();
                            if (value == null || value == "") {
                                errorFlag = false;
                                error = error + s + "不能为空;";
                            }
                        }
                        if (s.equals("机构名称")) orgName = dataMap.get(s).toString();
                        if (s.equals("单位ID")) buId = dataMap.get(s).toString();
                        if (s.equals("电话1")) phone1 = dataMap.get(s).toString();
                        if (s.equals("电话2")) phone2 = dataMap.get(s).toString();
                    }
                    //errorFlag
                    if (errorFlag) {
                        if (numberList.contains(number)) {
                            error = error + "数据库已存在此设备编码;";
                            errorFlag = false;
                        } else if (numberExcelList.contains(number)) {
                            error = error + "excel中已存在此设备编码;";
                            errorFlag = false;
                        }
                        if (!classify.contains(deviceClassify)) {
                            error = error + "设备分类编号不存在;";
                            errorFlag = false;
                        }
                        if (!type.contains(deviceType)) {
                            error = error + "设备类型编号不存在;";
                            errorFlag = false;
                        }
                        if (StrUtil.isNotBlank(buId) && !allBuIdList.contains(buId)) {
                            error = error + "单位ID不存在;";
                            errorFlag = false;
                        }
//                        if(StrUtil.isNotBlank(orgId) && !allOrgIdList.contains(orgId)){
//                            error = error + "机构ID不存在;";
//                            errorFlag = false;
//                        }
                        if (!regionIdList.contains(area)) {
                            error = error + "街道编号不存在;";
                            errorFlag = false;
                        }
//                        if(StrUtil.isNotBlank(phone1) && phone1.length()!=11){
//                            error = error + "电话1不为11位;";
//                            errorFlag = false;
//                        }
//                        if(StrUtil.isNotBlank(phone2) && phone2.length()!=11){
//                            error = error + "电话2不为11位;";
//                            errorFlag = false;
//                        }
                    }
                    //不符合的数据剔除，符合的保留
                    if (!errorFlag) {
                        LinkedHashMap<String, Object> erroMap = new LinkedHashMap<>();
                        erroMap.put("错误信息", error);
                        removeList.add(dataMap);
                        erroMap.putAll(dataMap);
                        errorList.add(erroMap);
                        errorFlag = true;
                    } else {
                        //新增机构
//                        if (StrUtil.isBlank(orgId)) {
//                            Organization organization = new Organization();
//                            organization.setDes(null);
//                            orgId = UUID.randomUUID().toString();
//                            organization.setId(orgId);
//                            organization.setName(orgName);
//                            organization.setPid(orgPId);
//                            insertOrganizationList.add(organization);
//                            orgMap.put(orgName, orgId);
//                            allOrgIdList.add(orgId);
//                        }
                        //新增企业
                        if (StrUtil.isBlank(buId)) {
                            Business business = new Business();
                            buId = UUID.randomUUID().toString();
                            business.setId(buId);
                            business.setOrgId(orgId);
                            business.setCreatetime(new Date());
                            business.setOneResponPersonName(dataMap.get("联系人").toString());
                            business.setOneResponPersonPhone(phone1);
                            business.setSafeResponPersonName(dataMap.get("联系人").toString());
                            business.setSafeResponPersonPhone(phone2);
                            business.setName(buName);
                            business.setAddr(buName);
                            business.setDel(false);
                            business.setArea(regionPidMap.get(area));
                            business.setAreaName(regionNameMap.get(area));
                            String allOrg = (String) getAllOrgId.get(orgId);
                            business.setOrgIds(allOrg);
                            insertBusinessList.add(business);
                            buMap.put(buName, buId);
                            allBuIdList.add(buId);
                        }
                        //新增设备
                        DeviceBusiness deviceBusiness = new DeviceBusiness();
                        deviceBusiness.setId(UUID.randomUUID().toString());
                        deviceBusiness.setNumber(number);
                        deviceBusiness.setBusinessId(buId);
                        deviceBusiness.setBusinessName(buName);
                        deviceBusiness.setDeviceClassify(deviceClassify);
                        deviceBusiness.setName(buName);
                        deviceBusiness.setOrgId(orgId);
                        String allOrg = (String) getAllOrgId.get(orgId);
                        deviceBusiness.setAllId(allOrg);
                        deviceBusiness.setPosition(dataMap.get("安装位置").toString());
                        if (StrUtil.isNotBlank(dataMap.get("安装时间").toString())) {
                            deviceBusiness.setInstalltime(dataMap.get("安装时间").toString());
                        } else {
                            deviceBusiness.setInstalltime(null);
                        }
                        deviceBusiness.setDeviceType(deviceType);
                        if (deviceClassify.equals("2")) {
                            if (dataMap.get("安装位置").toString().contains("水箱") || dataMap.get("安装位置").toString().contains("顶楼")) {
                                deviceBusiness.setWaterattr("2");
                            } else {
                                deviceBusiness.setWaterattr("1");
                            }
                        }
                        deviceBusiness.setInstallperson(dataMap.get("安装人员").toString());
                        deviceBusiness.setCreatetime(new Date());
                        deviceBusiness.setCurrentstate("1");
                        deviceBusiness.setNormalUpdateTime(DateUtil.now());
                        insertDeviceList.add(deviceBusiness);
                        numberExcelList.add(number);
                        errorFlag = true;
                    }
                }
                if (insertDeviceList != null && insertDeviceList.size() > 0) {
                    if (insertOrganizationList != null && insertOrganizationList.size() > 0) {
                        //rest请求系统设置模块批量新增机构
                    }
                    if (insertBusinessList != null && insertBusinessList.size() > 0) {//rest!!!!!!!!
                        params.put("busineslist", insertBusinessList);
                        makeDataForJSONForTokenMethod(params, "businessJava", "config", "businessAllAdd", "business", "post");
                        //rest请求一企一档模块批量新增机构
                    }
                    deviceMapper.insertZB(insertDeviceList);
                    //根据设备分类组装各个模块的设备集合，rest请求各个模块去批量添加设备
                    commit(session);
                }
            }
            //存错误list到缓存
            if (errorList != null && errorList.size() > 0) {
                String repath = ConfigKit.getStr("excelSavePath", "excel");
                StringBuffer url = WebUtil.getRequest().getRequestURL();
                String fileName = "import_Error(" + "导入错误信息" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
                webPath = url.toString().replace("/firefightingiot/uploadFile/deviceImport", "/firefightingiot/uploadFile/downloadExcel?fileName=" + fileName);
                ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
                // 一次性写出内容，使用默认样式
                writer.write(errorList);
                writer.setColumnWidth(1, 30);
                writer.setColumnWidth(2, 30);
                writer.setColumnWidth(3, 30);
                writer.renameSheet("导入错误信息");
                // 关闭writer，释放内存
                writer.close();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            closeSession(session);
        }
        excelList.removeAll(removeList);
        // 拼装返回结果
        JSONObject result = new JSONObject();
        result.put("ErrorNum", errorList.size());
        result.put("SuccesNum", excelList.size());
        result.put("webPath", webPath);
        return RespEntity.success(result);
    }

    /**
     * @Author YangYu
     * @Description 设备导入
     * @Date Created in 10:00 2023/4/14
     * @Param [params]
     */

    public RespEntity deviceImport(Map<String, Object> params) throws Exception {
        System.out.println("params+++++++++++"+params.toString());
        String webPath = "";
        //组装excel表应该有的列名
        Map<String, String> map = new LinkedHashMap<>();
        map.put("设备名称", "");
        map.put("设备编号", "");
        map.put("物联网卡号", "");
        map.put("传输装置编码", "");
        map.put("安装位置", "");
        //单位ID
        String businessId = params.get("businessId").toString();
        //设备分类
        String deviceClassify = params.get("deviceClassify").toString();
        //设备类型
        String deviceType = params.get("deviceType").toString();
        //产品ID
        String productId = params.get("productId").toString();
        //是否是子设备
        String isChildrens = params.get("isChildren").toString();
        Integer isChildren = Integer.parseInt(isChildrens);
        //时间
        String time = DateUtil.now();
        //获取单位信息
        Business business = deviceBusinessMapper.getBusiness(businessId);

        List<Map<String, Object>> excelList = (List<Map<String, Object>>) params.get("listData");//获取excel表中的数据
        List<Map<String, Object>> removeList = new ArrayList<>();//删除的list

        //获取目前有的设备编号
        List<String> numberList = deviceBusinessMapper.getNumber();

        //之后新增的设备
        List<String> numberExcelList = new ArrayList<>();
        //判断excel中的列名和应该有的列名是不是一致
        if (excelList != null && excelList.size() > 0) {
            Map<String, Object> excelMap = excelList.get(0);
            Set<String> set = excelMap.keySet();
            for (String s : set) {
                if (!map.containsKey(s)) {
                    return RespEntity.fail("文件表头不匹配");
                }
            }
        }
        List<LinkedHashMap<String, Object>> errorList = new ArrayList<>();//出错的list
        SqlSession session = getSqlSession();
        boolean errorFlag = true;
        try {
            DeviceBusinessMapper deviceMapper = getMapper(session, DeviceBusinessMapper.class);
            BigData data = new BigData(excelList);
            for (int i = 0; i < data.getNum(); i++) {
                //boolean insertFlag = false;
                //存储一千条要保存的DeviceBusiness集合
                List<DeviceBusiness> insertDeviceList = new ArrayList<>();
                //excel中一组数据
                List<Map<String, Object>> dataMapList = data.getData(i);
                for (Map<String, Object> dataMap : dataMapList) {
                    Set<String> set = dataMap.keySet();
                    //错误信息
                    String error = "";
                    //设备编号
                    String number = "";
                    //设备编号
                    String deviceName = "";
                    //安装位置
                    String adds = "";
                    //物联网卡号
                    String internetofthingsCardnum = "";
                    //传输装置编码
                    String transDeviceCode = "";
                    for (String s : set) {
                        if (dataMap.get(s) == null) dataMap.put(s, "");//防止下载错误list的时候，为空时错行
                        System.out.println(s + "------------------" + dataMap.get(s).toString());
                        //为空时为不符合的数据
                        if (s.equals("设备名称") || s.equals("设备编号") || s.equals("安装位置")) {
                            if (s.equals("设备名称")) deviceName = dataMap.get(s).toString();
                            if (s.equals("设备编号")) number = dataMap.get(s).toString();
                            if (s.equals("安装位置")) adds = dataMap.get(s).toString();
                            String value = dataMap.get(s).toString();
                            if (value == null || value == "") {
                                errorFlag = false;
                                error = error + s + "不能为空;";
                            }
                        }
                        if (s.equals("物联网卡号")) internetofthingsCardnum = dataMap.get(s).toString();
                        if (s.equals("传输装置编码")) transDeviceCode = dataMap.get(s).toString();
                    }
                    //errorFlag
                    if (errorFlag) {
                        if (numberList.contains(number)) {
                            error = error + "数据库已存在此设备编码;";
                            errorFlag = false;
                        } else if (numberExcelList.contains(number)) {
                            error = error + "excel中已存在此设备编码;";
                            errorFlag = false;
                        }
                    }
                    //不符合的数据剔除，符合的保留
                    if (!errorFlag) {
                        LinkedHashMap<String, Object> erroMap = new LinkedHashMap<>();
                        erroMap.put("错误信息", error);
                        removeList.add(dataMap);
                        erroMap.putAll(dataMap);
                        errorList.add(erroMap);
                        errorFlag = true;
                    } else {
                        //新增设备
                        DeviceBusiness deviceBusiness = new DeviceBusiness();
                        deviceBusiness.setId(UUID.randomUUID().toString());
                        deviceBusiness.setDeviceClassify(deviceClassify);
                        deviceBusiness.setOrgId(business.getOrgId());
                        deviceBusiness.setBusinessId(businessId);
                        deviceBusiness.setBusinessName(business.getName());
                        deviceBusiness.setName(deviceName);
                        deviceBusiness.setNumber(number);
                        deviceBusiness.setInternetofthingsCardnum(internetofthingsCardnum);
                        if (params.get("transDeviceCode").equals("NO")){
                            deviceBusiness.setTransDeviceCode(transDeviceCode);
                        }else {
                            deviceBusiness.setTransDeviceCode(params.get("transDeviceCode").toString());
                        }
                        deviceBusiness.setDeviceType(deviceType);
                        deviceBusiness.setInstalltime(time);
                        deviceBusiness.setPosition(adds);
                        deviceBusiness.setLon(business.getLon());
                        deviceBusiness.setLat(business.getLat());
                        deviceBusiness.setAllId(business.getOrgIds());
                        deviceBusiness.setProductId(productId);
                        deviceBusiness.setIsChildren(isChildren);
                        if (deviceClassify.equals("2")) {
                            if (deviceType.equals("1") || deviceType.equals("2")) {
                                deviceBusiness.setWaterattr("2");
                                deviceBusiness.setSpec("3*3*3");
                            } else {
                                deviceBusiness.setWaterattr("1");
                            }
                        }
                        if (deviceClassify.equals("11") || deviceClassify.equals("12")|| deviceClassify.equals("13")|| deviceClassify.equals("14")|| deviceClassify.equals("15")|| deviceClassify.equals("16")|| deviceClassify.equals("17")|| deviceClassify.equals("6")){
                            deviceBusiness.setPlayType("01");
                        }
                        deviceBusiness.setCreatetime(new Date());
                        deviceBusiness.setCurrentstate("3");
                        deviceBusiness.setNormalUpdateTime(time);
                        insertDeviceList.add(deviceBusiness);
                        numberExcelList.add(number);
                        errorFlag = true;
                    }
                }
                if (insertDeviceList != null && insertDeviceList.size() > 0) {
                    deviceMapper.insertZB(insertDeviceList);
                    //根据设备分类组装各个模块的设备集合，rest请求各个模块去批量添加设备
                    commit(session);
                }
            }
            //存错误list到缓存
            if (errorList != null && errorList.size() > 0) {
                String repath = ConfigKit.getStr("excelSavePath", "excel");
                StringBuffer url = WebUtil.getRequest().getRequestURL();
                String fileName = "import_Error(" + "导入错误信息" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
                webPath = url.toString().replace("/firefightingiot/uploadFile/deviceImport", "/firefightingiot/uploadFile/downloadExcel?fileName=" + fileName);
                ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
                // 一次性写出内容，使用默认样式
                writer.write(errorList);
                writer.setColumnWidth(1, 30);
                writer.setColumnWidth(2, 30);
                writer.setColumnWidth(3, 30);
                writer.renameSheet("导入错误信息");
                // 关闭writer，释放内存
                writer.close();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            closeSession(session);
        }
        excelList.removeAll(removeList);
        // 拼装返回结果
        JSONObject result = new JSONObject();
        result.put("ErrorNum", errorList.size());
        result.put("SuccesNum", excelList.size());
        result.put("webPath", webPath);
        return RespEntity.success(result);
    }

    /**
     * 设备导出
     *
     * @param params
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> getDeviceTemplte(@RequestParam Map<String, Object> params) throws Exception {
        //处理支持form-data和json两种方式
        JSONObject jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("+++++++++++DeviceTemplte+++++++++" + jsonParam);
        com.alibaba.fastjson.JSONObject usre = userInfo(jsonParam, "systemsetup", "userInfo", "systemsetup");
        String homeId = usre.getString("homeId");
        String userType = usre.getString("type");
        if (userType.equals("1")) {//为机构用户
            //rest请求系统设置模块的机构和子机构列表接口
            if (StrUtil.isNotBlank(jsonParam.getStr("businessId"))) {//机构用户访问单位用户的数据
                jsonParam.put("businessId", jsonParam.getStr("businessId"));
            } else {
                jsonParam.put("orgId", homeId);
            }
        } else if (userType.equals("2")) {//为单位用户
            jsonParam.put("businessId", homeId);
        }
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("name", "设备名称");
        map.put("number", "设备编号");
        map.put("internetofthingsCardnum", "物联网卡号");
        map.put("deviceTypeName", "设备类型");
        map.put("position", "安装位置");
        map.put("currentstateName", "设备状态");
        map.put("productName", "产品型号");
        //fieldList.add(map);
        List<LinkedHashMap<String, String>> dataList = deviceBusinessMapper.getDeviceList(jsonParam);
        fieldList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String code = UUID.randomUUID().toString();
        String webPath = "";
        String fileName = "设备表" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        webPath = url.toString().replace("/getTemplte", "/downloadExcel?fileName=" + fileName);
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 40);
        writer.setColumnWidth(2, 40);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 40);
        writer.setColumnWidth(5, 20);
        writer.setColumnWidth(6, 30);
        writer.setHeaderAlias(map);
        writer.write(fieldList);
        writer.renameSheet("设备");
        // 关闭writer，释放内存
        writer.close();
        //返回二进制流
        return downloadExcel(fileName);
    }
    /**
     * 设备导出（新）
     * @param params
     * @return
     * @throws Exception
     */
    public RespEntity getDeviceExport(Map<String, Object> params) {
        //处理支持form-data和json两种方式
        JSONObject jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (userType.equals("1")) {//为机构用户
            //rest请求系统设置模块的机构和子机构列表接口
            if (StrUtil.isNotBlank(jsonParam.getStr("businessId"))) {//机构用户访问单位用户的数据
                jsonParam.put("businessId", jsonParam.getStr("businessId"));
            } else {
                jsonParam.put("orgId", homeId);
            }
        } else if (userType.equals("2")) {//为单位用户
            jsonParam.put("businessId", homeId);
        }
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("name", "设备名称");
        map.put("number", "设备编号");
        map.put("internetofthingsCardnum", "物联网卡号");
        map.put("deviceTypeName", "设备类型");
        map.put("position", "安装位置");
        map.put("currentstateName", "设备状态");
        map.put("productName", "产品型号");
        if (jsonParam.containsKey("deviceClassify") && StrUtil.isNotBlank(jsonParam.getStr("deviceClassify"))){
            if (jsonParam.getStr("deviceClassify").equals("1")){
                map.put("aVoltageValue", "A相电压");
                map.put("bVoltageValue", "B相电压");
                map.put("cVoltageValue", "C相电压");
                map.put("aElectricValue", "A相电流");
                map.put("bElectricValue", "B相电流");
                map.put("cElectricValue", "C相电流");
                map.put("dualElectricValue", "剩余电流");
                map.put("aTempValue", "A线温度");
                map.put("bTempValue", "B线温度");
                map.put("cTempValue", "C线温度");
                map.put("nTempValue", "N线温度");
                map.put("activeElectric", "总电能");
                map.put("allActivePower", "总有功功率");
                map.put("allPowerFactor", "总功率因数");
                String oneTableName = "device_normal_log_electric_fire_"+ DayUtil.getToday();
                jsonParam.put("tableName",oneTableName);
            }else if (jsonParam.getStr("deviceClassify").equals("2")){
                map.put("waterValue", "液位/水压");
            }else if (jsonParam.getStr("deviceClassify").equals("3")){
                map.put("smokeConcentration", "烟雾浓度");
                map.put("temperature", "温度");
                map.put("battery", "电量");
                map.put("signal", "信号");
                String oneTableName = "device_normal_log_smoke_"+ DayUtil.getToday();
                jsonParam.put("tableName",oneTableName);
            }
        }
        List<LinkedHashMap<String, String>> dataList = deviceBusinessMapper.getDeviceNewList(jsonParam);
        fieldList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        String fileName = "设备表" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        String webPath = ConfigKit.getStr("path", "excel")+fileName;
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 40);
        writer.setColumnWidth(2, 40);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 40);
        writer.setColumnWidth(5, 20);
        writer.setColumnWidth(6, 30);
        if (jsonParam.containsKey("deviceClassify") && StrUtil.isNotBlank(jsonParam.getStr("deviceClassify"))) {
            if (jsonParam.getStr("deviceClassify").equals("1")) {
                writer.setColumnWidth(7, 20);
                writer.setColumnWidth(8, 20);
                writer.setColumnWidth(9, 20);
                writer.setColumnWidth(10, 20);
                writer.setColumnWidth(11, 20);
                writer.setColumnWidth(12, 20);
                writer.setColumnWidth(13, 20);
                writer.setColumnWidth(14, 20);
                writer.setColumnWidth(15, 20);
                writer.setColumnWidth(16, 20);
                writer.setColumnWidth(17, 20);
                writer.setColumnWidth(18, 20);
                writer.setColumnWidth(19, 20);
                writer.setColumnWidth(20, 20);
            } else if (jsonParam.getStr("deviceClassify").equals("2")) {
                writer.setColumnWidth(7, 20);
            }else if (jsonParam.getStr("deviceClassify").equals("2")){
                writer.setColumnWidth(7, 20);
                writer.setColumnWidth(8, 20);
                writer.setColumnWidth(9, 20);
                writer.setColumnWidth(10, 20);
            }
        }
        writer.setHeaderAlias(map);
        writer.write(fieldList);
        writer.renameSheet("设备");
        // 关闭writer，释放内存
        writer.close();
        Map<String, Object> fileMap = new HashMap<>();
        fileMap.put("filePath", webPath);
        fileMap.put("fileName", fileName);
        return RespEntity.success(fileMap);
    }
    /**
     * 报警记录导出
     *
     * @param params
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> exportDeviceAlarmLog(@RequestParam Map<String, Object> params) throws Exception {
        //处理支持form-data和json两种方式
        JSONObject jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        com.alibaba.fastjson.JSONObject usre = userInfo(jsonParam, "systemsetup", "userInfo", "systemsetup");
        String homeId = usre.getString("homeId");
        String userType = usre.getString("type");
        if (userType.equals("1")) {//为机构用户
            //rest请求系统设置模块的机构和子机构列表接口
            if (StrUtil.isNotBlank(jsonParam.getStr("businessId"))) {//机构用户访问单位用户的数据
                jsonParam.put("businessId", jsonParam.getStr("businessId"));
            } else {
                jsonParam.put("orgId", homeId);
            }
        } else if (userType.equals("2")) {//为单位用户
            jsonParam.put("businessId", homeId);
        }
        if (jsonParam.containsKey("isHandle")) {
            if (jsonParam.getBool("isHandle")) jsonParam.put("isHandle", 1);
            if (!jsonParam.getBool("isHandle")) jsonParam.put("isHandle", 0);
        }
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("businessName", "所属单位");
        map.put("alarmTypeName", "报警类型");
        map.put("number", "设备编号");
        map.put("content", "报警内容");
        map.put("position", "位置");
        map.put("alarmtime", "报警时间");
        map.put("isHandleName", "是否处置");
        map.put("handletime", "处置时间");
        map.put("handlePerson", "处置人员");
        map.put("handleRemark", "处置备注");
        //fieldList.add(map);
        List<LinkedHashMap<String, String>> dataList = deviceAlarmLogMapper.exportDeviceAlarmLog(jsonParam);
        fieldList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String code = UUID.randomUUID().toString();
        String webPath = "";
        String fileName = "报警记录" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        webPath = url.toString().replace("/exportDeviceAlarmLog", "/downloadExcel?fileName=" + fileName);
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 20);
        writer.setColumnWidth(3, 40);
        writer.setColumnWidth(4, 40);
        writer.setColumnWidth(5, 20);
        writer.setColumnWidth(6, 15);
        writer.setColumnWidth(7, 20);
        writer.setColumnWidth(8, 15);
        writer.setColumnWidth(9, 40);
        writer.setHeaderAlias(map);
        writer.write(fieldList);
        writer.renameSheet("报警记录");
        // 关闭writer，释放内存
        writer.close();
        //返回二进制流
        return downloadExcel(fileName);
    }

    /**
     * 机构导出
     *
     * @param params
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> getOrgTemplte(JSONObject params) throws Exception {
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("机构名称", "");
        map.put("机构Id", "");
        fieldList.add(map);
        List<Map<String, String>> dataList = (List<Map<String, String>>) makeDataForJSON(params, "systemsetup", "config", "getOrgList", "systemsetup");
        fieldList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String code = UUID.randomUUID().toString();
        String webPath = "";
        String fileName = "机构表" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        webPath = url.toString().replace("/getTemplte", "/downloadExcel?fileName=" + fileName);
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 50);
        writer.write(fieldList);
        writer.renameSheet("机构");
        // 关闭writer，释放内存
        writer.close();
        //返回二进制流
        return downloadExcel(fileName);
    }

    /**
     * 行政区划导出
     *
     * @param params
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> getRegionTemplte(JSONObject params) throws Exception {
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("行政区划上级名称", "");
        map.put("行政区划上级ID", "");
        map.put("行政区划名称", "");
        map.put("行政区划ID", "");
        fieldList.add(map);
        List<Map<String, String>> dataList = (List<Map<String, String>>) makeDataForJSON(params, "businessJava", "config", "getGegionList", "business");
        fieldList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String code = UUID.randomUUID().toString();
        String webPath = "";
        String fileName = "行政区划表" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        webPath = url.toString().replace("/getTemplte", "/downloadExcel?fileName=" + fileName);
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 50);
        writer.write(fieldList);
        writer.renameSheet("行政区划");
        // 关闭writer，释放内存
        writer.close();
        //返回二进制流
        return downloadExcel(fileName);
    }

    /**
     * 单位导出
     *
     * @param params
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> getBusinessTemplte(JSONObject params) throws Exception {
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("行政区划ID", "");
        map.put("行政区划名称", "");
        map.put("单位名称", "");
        map.put("单位Id", "");
        fieldList.add(map);
        List<Map<String, String>> dataList = (List<Map<String, String>>) makeDataForJSON(params, "businessJava", "config", "getBusiness", "business");
        fieldList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String code = UUID.randomUUID().toString();
        String webPath = "";
        String fileName = "单位表" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        webPath = url.toString().replace("/getTemplte", "/downloadExcel?fileName=" + fileName);
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 50);
        writer.write(fieldList);
        writer.renameSheet("单位");
        // 关闭writer，释放内存
        writer.close();
        //返回二进制流
        return downloadExcel(fileName);
    }

    protected String[] FILE_UPLOAD_IMG_EXTS = {"jpg", "png", "gif", "jpeg", "bmp", "zip", "xlsx", "txt", "docx", "doc", "xls", "jar", "mp4", "mp3", "pdf"};

    /**
     * @Author YangYu
     * @Description led屏上传视频
     * @Date Created in 16:41 2021/9/13
     * @Param [params, request]
     */

    public RespEntity uploadLedVideoFile(String number, String homeId, HttpServletRequest request) {

        //错误信息
        Map<String, Object> errorMap = new HashMap<>();
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (!commonsMultipartResolver.isMultipart(request)) {
            errorMap.put("errorMsg", "无法从Request中获取文件对象");
            return RespEntity.fail(errorMap.toString());
        }
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
        String paths = "";
        Map<String, Object> fileMap = new HashMap<>();
        while (fileNames.hasNext()) {
            String fileName = fileNames.next();
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(fileName);
            if (multipartFile == null) {
                errorMap.put("errorMsg", StrUtil.format("未成功获取文件对象", fileName));
                return RespEntity.fail(errorMap.toString());
            } else if (multipartFile.isEmpty()) {
                errorMap.put("errorMsg", StrUtil.format("成功获取文件对象,但无法获取名为{}的文件", fileName));
                return RespEntity.fail(errorMap.toString());
            }
            // 原始文件名
            String oldFileName = multipartFile.getOriginalFilename();
            List<LedUploadFile> ledUploadFileList = ledUploadFileMapper.selectList(new QueryWrapper<LedUploadFile>().eq("name", oldFileName));
            if (ledUploadFileList.size() != 0) {
                return RespEntity.fail("文件已存在!");
            }
            String repath = ConfigKit.getStr("ledFileSavePath", "upload");
            String webPath = ConfigKit.getStr("ledWebPath", "upload");
            String[] arrTmp = oldFileName.split("\\.");
            String ext = arrTmp[arrTmp.length - 1];
            int count = 0;
            for (String _ext : FILE_UPLOAD_IMG_EXTS) {
                if (_ext.equalsIgnoreCase(ext)) {
                    count++;
                }
            }
            if (count < 1) {
                return RespEntity.fail(StrUtil.format("文件后缀{}不合法", ext));
            }
            //新文件名
            String newFileName = number + "." + ext;
            File file = new File(repath);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(repath + "/" + oldFileName);
            try {
                multipartFile.transferTo(file);
                fileMap.put("filePath", webPath + "/" + oldFileName);
                fileMap.put("fileName", multipartFile.getOriginalFilename());
                LedUploadFile ledUploadFile = new LedUploadFile();
                ledUploadFile.setId(UUID.randomUUID().toString());
                ledUploadFile.setName(oldFileName);
                ledUploadFile.setCreatetime(DateUtil.date());
                ledUploadFile.setHomeId(homeId);
                if ("mp4".equals(ext)) {
                    ledUploadFile.setType("2");
                } else if ("jpg".equals(ext)) {
                    ledUploadFile.setType("1");
                }
                ledUploadFileMapper.insert(ledUploadFile);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                errorMap.put("errorMsg", StrUtil.format("图片保存失败:{}", e.getMessage()));
                return RespEntity.fail(errorMap.toString());
            }
        }
        return RespEntity.success(fileMap);
    }

    /**
     * @Author YangYu
     * @Description IP音柱上传音频
     * @Date Created in 16:41 2021/9/13
     * @Param [params, request] homeId 机构id或者单位id
     */

    public RespEntity uploadIpAudioFile(String homeId, HttpServletRequest request) {
        List<String> fileNameLsit = new ArrayList<String>();
        Map<String, Object> errorMap = new HashMap<>();
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (!commonsMultipartResolver.isMultipart(request)) {
            errorMap.put("errorMsg", "无法从Request中获取文件对象");
            return RespEntity.fail(errorMap.toString());
        }
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
        String paths = "";
        Map<String, Object> fileMap = new HashMap<>();
        while (fileNames.hasNext()) {
            String fileName = fileNames.next();
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(fileName);
            if (multipartFile == null) {
                errorMap.put("errorMsg", StrUtil.format("未成功获取文件对象", fileName));
                return RespEntity.fail(errorMap.toString());
            } else if (multipartFile.isEmpty()) {
                errorMap.put("errorMsg", StrUtil.format("成功获取文件对象,但无法获取名为{}的文件", fileName));
                return RespEntity.fail(errorMap.toString());
            }
            String repath = ConfigKit.getStr("ipFileSavePath", "upload");
            //String webPath = ConfigKit.getStr("webPath1", "upload");
            // 原始文件名
            String oldFileName = multipartFile.getOriginalFilename();
            String[] arrTmp = oldFileName.split("\\.");
            String ext = arrTmp[arrTmp.length - 1];
            int count = 0;
            for (String _ext : FILE_UPLOAD_IMG_EXTS) {
                if (_ext.equalsIgnoreCase(ext)) {
                    count++;
                }
            }
            if (count < 1) {
                return RespEntity.fail(StrUtil.format("文件后缀{}不合法", ext));
            }
            //String newFileName = number + "." + ext;
            File file = new File(repath);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(repath + "/" + oldFileName);
            try {
                multipartFile.transferTo(file);
                fileMap.put("filePath", repath + "\\" + oldFileName);
                fileMap.put("fileName", multipartFile.getOriginalFilename());
                String filePath = repath + "\\" + oldFileName;
                //存储的上传本来的名称
                String fileName1 = multipartFile.getOriginalFilename();
                IpSoundFileName ipSoundFileName = new IpSoundFileName();
                ipSoundFileName.setId(UUID.randomUUID().toString());
                ipSoundFileName.setFilename(fileName1);
                ipSoundFileName.setFilepath(filePath);
                ipSoundFileName.setCreatetime(DateUtil.date());
                ipSoundFileName.setHomeId(homeId);
                ipSoundFileName.setState("1");
                //数据库中不能用相同的文件名
                List<IpSoundFileName> ipSoundFileList = this.ipSoundFileNameMapper.selectList(new QueryWrapper<IpSoundFileName>().eq("filename", fileName1));
                if (ipSoundFileList.size() > 0) {
                    IpSoundFileName ipSoundFileName1 = ipSoundFileList.get(0);
                    String id = ipSoundFileName1.getId();
                    this.ipSoundFileNameMapper.deleteById(id);
                }
                this.ipSoundFileNameMapper.insert(ipSoundFileName);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                errorMap.put("errorMsg", StrUtil.format("图片保存失败:{}", e.getMessage()));
                return RespEntity.fail(errorMap.toString());
            }
        }
        return RespEntity.success(fileMap);
    }

    /**
     * @Author YangYu
     * @Description 卸油证据链上传
     * @Date Created in 11:23 2021/11/19
     * @Param [request]
     */

    public RespEntity uploadChainOfEvidenceFile(HttpServletRequest request) {

        //错误信息
        Map<String, Object> errorMap = new HashMap<>();
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (!commonsMultipartResolver.isMultipart(request)) {
            errorMap.put("errorMsg", "无法从Request中获取文件对象");
            return RespEntity.fail(errorMap.toString());
        }
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
        String paths = "";
        Map<String, Object> fileMap = new HashMap<>();
        while (fileNames.hasNext()) {
            String fileName = fileNames.next();
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(fileName);
            if (multipartFile == null) {
                errorMap.put("errorMsg", StrUtil.format("未成功获取文件对象", fileName));
                return RespEntity.fail(errorMap.toString());
            } else if (multipartFile.isEmpty()) {
                errorMap.put("errorMsg", StrUtil.format("成功获取文件对象,但无法获取名为{}的文件", fileName));
                return RespEntity.fail(errorMap.toString());
            }
            // 原始文件名
            String oldFileName = multipartFile.getOriginalFilename();
//			List<LedUploadFile> ledUploadFileList = ledUploadFileMapper.selectList(new QueryWrapper<LedUploadFile>().eq("name",oldFileName));
//			if (ledUploadFileList.size() !=0){
//				return RespEntity.fail("文件已存在!");
//			}
            String repath = ConfigKit.getStr("savePathFile", "upload")+"/AOX-H01/file/"+ DateUtil.now().split(" ")[0].replace("-","")+"/";
            //String repath = "e:/";
            StringBuffer url = request.getRequestURL();
            String webPath = ConfigKit.getStr("webFilePath", "upload") + "AOX-H01/file/" + DateUtil.now().split(" ")[0].replace("-", "") + "/";
            String[] arrTmp = oldFileName.split("\\.");
            String ext = arrTmp[arrTmp.length - 1];
            int count = 0;
            for (String _ext : FILE_UPLOAD_IMG_EXTS) {
                if (_ext.equalsIgnoreCase(ext)) {
                    count++;
                }
            }
            if (count < 1) {
                return RespEntity.fail(StrUtil.format("文件后缀{}不合法", ext));
            }
            //新文件名
            //String newFileName = number + "." + ext;
            File file = new File(repath);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(repath + oldFileName);
            try {
                multipartFile.transferTo(file);
                ChainofcvidenceUploadFile chainofcvidenceUploadFile = new ChainofcvidenceUploadFile();
                chainofcvidenceUploadFile.setId(UUID.randomUUID().toString());
                chainofcvidenceUploadFile.setName(oldFileName);
                chainofcvidenceUploadFile.setCreatetime(DateUtil.date());
                String[] arrOldFileName = oldFileName.split("_");
                chainofcvidenceUploadFile.setNumber(arrOldFileName[0]);
                chainofcvidenceUploadFile.setPath(webPath + oldFileName);
                chainofcvidenceUploadFileMapper.insert(chainofcvidenceUploadFile);
                fileMap.put("filePath", webPath + oldFileName);
                fileMap.put("fileName", multipartFile.getOriginalFilename());
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                errorMap.put("errorMsg", StrUtil.format("图片保存失败:{}", e.getMessage()));
                return RespEntity.fail(errorMap.toString());
            }
        }
        return RespEntity.success(fileMap);
    }

    /**
     * @Author YangYu
     * @Description 导入
     * @Date Created in 10:46 2022/9/13
     * @Param [params]
     */

    public RespEntity maintenanceDeviceImport(Map<String, Object> params) throws Exception {

        String webPath = "";
        //组装excel表应该有的列名
        Map<String, String> map = new LinkedHashMap<>();
        map.put("设备名称", "");
        map.put("设备号", "");
        map.put("设备类型ID", "");
        map.put("设备类型名称", "");
        map.put("系统ID", "");
        //获取excel表中的数据
        List<Map<String, Object>> excelList = (List<Map<String, Object>>) params.get("listData");
        //删除的list
        List<Map<String, Object>> removeList = new ArrayList<>();
        //判断excel中的列名和应该有的列名是不是一致
        if (excelList != null && excelList.size() > 0) {
            Map<String, Object> excelMap = excelList.get(0);
            Set<String> set = excelMap.keySet();
            for (String s : set) {
                if (!map.containsKey(s)) {
                    return RespEntity.fail("文件表头不匹配");
                }
            }
        }
        //出错的list
        List<LinkedHashMap<String, Object>> errorList = new ArrayList<>();
        SqlSession session = getSqlSession();
        boolean errorFlag = true;
        try {
            String businessId = params.get("businessId").toString();
            String partitionId = params.get("partitionId").toString();
            BigData data = new BigData(excelList);
            //用于存储导入文档中已有的设备号
            List<String> numberForImpList = new ArrayList<>();
            //设备号
            List<String> deviceList = deviceBusinessMapper.getMaintenanceDeviceNumber();
            for (int i = 0; i < data.getNum(); i++) {
                List<MaintenanceDevice> insertDeviceList = new ArrayList<>();
                //excel中一组数据
                List<Map<String, Object>> dataMapList = data.getData(i);
                for (Map<String, Object> dataMap : dataMapList) {
                    Set<String> set = dataMap.keySet();
                    //错误信息
                    String error = "";
                    //设备名称
                    String name = "";
                    //设备号
                    String number = "";
                    //设备类型ID
                    String deviceTypeId = "";
                    //设备类型名称
                    String deviceTypeName = "";
                    //系统ID
                    String systemId = "";
                    for (String s : set) {
                        //防止下载错误list的时候，为空时错行
                        if (dataMap.get(s) == null) dataMap.put(s, "");
                        System.out.println(s + "------------------" + dataMap.get(s).toString());
                        if (s.equals("设备名称") || s.equals("设备号") || s.equals("设备类型ID") || s.equals("设备类型名称") || s.equals("系统ID")){
                            if (s.equals("设备名称")) name = dataMap.get(s).toString();
                            if (s.equals("设备号")) number = dataMap.get(s).toString();
                            if (s.equals("设备类型ID")) deviceTypeId = dataMap.get(s).toString();
                            if (s.equals("设备类型名称")) deviceTypeName = dataMap.get(s).toString();
                            if (s.equals("系统ID")) systemId = dataMap.get(s).toString();
                            String value = dataMap.get(s).toString();
                            if (value == null || value == "") {
                                errorFlag = false;
                                error = error + s + "不能为空;";
                            }
                        }
                    }
                    //数据库和文档中的判断逻辑
                    if (errorFlag) {
                        if(numberForImpList.contains(number)){
                            errorFlag = false;
                            error = error + "文档中已经导入过此设备号;";
                        }
                        if(deviceList.contains(number)){
                            errorFlag = false;
                            error = error + "数据库中已经存在此设备号;";
                        }
                    }
                    //不符合的数据剔除，符合的保留
                    if (!errorFlag) {
                        LinkedHashMap<String, Object> erroMap = new LinkedHashMap<>();
                        erroMap.put("错误信息", error);
                        removeList.add(dataMap);
                        erroMap.putAll(dataMap);
                        errorList.add(erroMap);
                        errorFlag = true;
                    } else {
                        MaintenanceDevice maintenanceDevice = new MaintenanceDevice();
                        maintenanceDevice.setId(UUID.randomUUID().toString());
                        maintenanceDevice.setName(name);
                        maintenanceDevice.setNumber(number);
                        maintenanceDevice.setDeviceTypeId(deviceTypeId);
                        maintenanceDevice.setDeviceTypeName(deviceTypeName);
                        maintenanceDevice.setBusinessId(businessId);
                        maintenanceDevice.setPartitionId(partitionId);
                        maintenanceDevice.setSystemId(systemId);
                        insertDeviceList.add(maintenanceDevice);
                        numberForImpList.add(number);
                    }
                }
                if (insertDeviceList != null && insertDeviceList.size() > 0) {
                    deviceBusinessMapper.insertZBMaintenanceDevice(insertDeviceList);
                }
                //存错误list到缓存
                if (errorList != null && errorList.size() > 0) {
                    String repath = ConfigKit.getStr("excelSavePath", "maintenanceExcel");
                    StringBuffer url = WebUtil.getRequest().getRequestURL();
                    String fileName = "import_Error(" + "导入错误信息" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
                    //webPath = "https://file.wiscloud.online/maintenanceDeviceImport/"+fileName;
                    webPath = "https://aq.wisdiot.com/uploads/maintenanceDeviceImport/"+fileName;
                    ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
                    // 一次性写出内容，使用默认样式
                    writer.write(errorList);
                    writer.setColumnWidth(1, 30);
                    writer.setColumnWidth(2, 30);
                    writer.setColumnWidth(3, 30);
                    writer.renameSheet("导入错误信息");
                    // 关闭writer，释放内存
                    writer.close();
                }
            }
        }catch (Exception e) {
            throw e;
        }finally {
            closeSession(session);
        }
        excelList.removeAll(removeList);
        // 拼装返回结果
        JSONObject result = new JSONObject();
        result.put("ErrorNum", errorList.size());
        result.put("SuccesNum", excelList.size());
        result.put("webPath", webPath);
        return RespEntity.success(result);
    }
    /**
     * @Author YangYu
     * @Description 单位导入
     * @Date Created in 10:46 2022/9/13
     * @Param [params]
     */

    public RespEntity businessImport(Map<String, Object> params) throws Exception {

        String webPath = "";
        //组装excel表应该有的列名
        Map<String, String> map = new LinkedHashMap<>();
        map.put("企业名称", "");
        map.put("企业代码", "");
        map.put("经度", "");
        map.put("纬度", "");
        map.put("详细地址", "");
        map.put("机构ID", "");
        map.put("消防第一负责人", "");
        map.put("消防第一负责人电话", "");
        map.put("消防安全负责人", "");
        map.put("消防安全负责人电话", "");
        map.put("消防安全管理人", "");
        map.put("消防安全管理人电话", "");
        //获取excel表中的数据
        List<Map<String, Object>> excelList = (List<Map<String, Object>>) params.get("listData");
        //删除的list
        List<Map<String, Object>> removeList = new ArrayList<>();
        //判断excel中的列名和应该有的列名是不是一致
        if (excelList != null && excelList.size() > 0) {
            Map<String, Object> excelMap = excelList.get(0);
            Set<String> set = excelMap.keySet();
            for (String s : set) {
                if (!map.containsKey(s)) {
                    return RespEntity.fail("文件表头不匹配");
                }
            }
        }
        //出错的list
        List<LinkedHashMap<String, Object>> errorList = new ArrayList<>();
        SqlSession session = getSqlSession();
        boolean errorFlag = true;
        try {
            String area = params.get("area").toString();
            String areaName = params.get("areaName").toString();
            List<Map<String,Object>> orgList = deviceBusinessMapper.getOrgList();
            //获得当前时间
            DateTime createtime = DateUtil.date();
            Calendar calendar = new GregorianCalendar();
            Date expiretime = createtime;
            calendar.setTime(expiretime);
            calendar.add(Calendar.YEAR, 1);//把日期往后增加一年.整数往后推,负数往前移动
            expiretime=calendar.getTime();
            BigData data = new BigData(excelList);

            for (int i = 0; i < data.getNum(); i++) {
                List<Business> insertBusinessList = new ArrayList<>();
                //excel中一组数据
                List<Map<String, Object>> dataMapList = data.getData(i);
                for (Map<String, Object> dataMap : dataMapList) {
                    Set<String> set = dataMap.keySet();
                    //错误信息
                    String error = "";
                    //设备名称
                    String name = "";
                    //企业代码
                    String enterpriseCode = "";
                    //经度
                    String lon = "";
                    //纬度
                    String lat = "";
                    //详细地址
                    String addr = "";
                    //机构ID
                    String orgId = "";
                    //消防第一责任人姓名
                    String oneResponPersonName = "";
                    //消防第一责任人电话
                    String oneResponPersonPhone = "";
                    //消防安全责任人姓名
                    String safeResponPersonName = "";
                    //消防安全责任人电话
                    String safeResponPersonPhone = "";
                    //消防安全管理人姓名
                    String safeManagePersonName = "";
                    //消防安全管理人电话
                    String safeManagePersonPhone = "";
                    for (String s : set) {
                        //防止下载错误list的时候，为空时错行
                        if (dataMap.get(s) == null) dataMap.put(s, "");
                        System.out.println(s + "------------------" + dataMap.get(s).toString());
                        if (s.equals("企业名称") || s.equals("企业代码") || s.equals("经度") || s.equals("纬度") || s.equals("详细地址")|| s.equals("机构ID")|| s.equals("消防第一负责人")|| s.equals("消防第一负责人电话")|| s.equals("消防安全负责人")|| s.equals("消防安全负责人电话")|| s.equals("消防安全管理人")|| s.equals("消防安全管理人电话")){
                            if (s.equals("企业名称")) name = dataMap.get(s).toString();
                            if (s.equals("企业代码")) enterpriseCode = dataMap.get(s).toString();
                            if (s.equals("经度")) lon = dataMap.get(s).toString();
                            if (s.equals("纬度")) lat = dataMap.get(s).toString();
                            if (s.equals("详细地址")) addr = dataMap.get(s).toString();
                            if (s.equals("机构ID")) orgId = dataMap.get(s).toString();
                            if (s.equals("消防第一负责人")) oneResponPersonName = dataMap.get(s).toString();
                            if (s.equals("消防第一负责人电话")) oneResponPersonPhone = dataMap.get(s).toString();
                            if (s.equals("消防安全负责人")) safeResponPersonName = dataMap.get(s).toString();
                            if (s.equals("消防安全负责人电话")) safeResponPersonPhone = dataMap.get(s).toString();
                            if (s.equals("消防安全管理人")) safeManagePersonName = dataMap.get(s).toString();
                            if (s.equals("消防安全管理人电话")) safeManagePersonPhone = dataMap.get(s).toString();
                            String value = dataMap.get(s).toString();
                            if (value == null || value == "") {
                                if (!s.equals("企业代码")){
                                    errorFlag = false;
                                    error = error + s + "不能为空;";
                                }
                            }
                        }
                    }
                    //数据库和文档中的判断逻辑
                    if (errorFlag) {

                    }
                    //不符合的数据剔除，符合的保留
                    if (!errorFlag) {
                        LinkedHashMap<String, Object> erroMap = new LinkedHashMap<>();
                        erroMap.put("错误信息", error);
                        removeList.add(dataMap);
                        erroMap.putAll(dataMap);
                        errorList.add(erroMap);
                        errorFlag = true;
                    } else {
                        Business business = new Business();
                        business.setId(UUID.randomUUID().toString());
                        business.setOrgId(orgId);
                        business.setName(name);
                        business.setLon(lon);
                        business.setLat(lat);
                        business.setAddr(addr);
                        business.setFireRating("001e7548-8735-4b31-b30b-c9361a62c904");
                        business.setUnitProperty("001e7548-8735-4b31-b30b-c9361a62c907");
                        business.setEnterpriseCode(enterpriseCode);
                        business.setHighRisk("0");
                        business.setArea(area);
                        business.setAreaName(areaName);
                        business.setOneResponPersonName(oneResponPersonName);
                        business.setOneResponPersonPhone(oneResponPersonPhone);
                        business.setSafeResponPersonName(safeResponPersonName);
                        business.setSafeResponPersonPhone(safeResponPersonPhone);
                        business.setSafeManagePersonName(safeManagePersonName);
                        business.setSafeManagePersonPhone(safeManagePersonPhone);
                        business.setIndustry("13");
                        business.setUnitCategory("01");
                        business.setFireDepartmentId("010107");
                        business.setIndustryAuthoritiesId("01010D");
                        for (Map<String,Object> objectMap : orgList){
                            if (objectMap.get("id").equals(orgId)){
                                business.setOrgIds(objectMap.get("allId").toString());
                                break;
                            }
                        }
                        business.setExpiretime(expiretime);
                        insertBusinessList.add(business);
                    }
                }
                if (insertBusinessList != null && insertBusinessList.size() > 0) {
                    deviceBusinessMapper.insertBusinessZB(insertBusinessList);
                }
                //存错误list到缓存
                if (errorList != null && errorList.size() > 0) {
                    String repath = ConfigKit.getStr("excelSavePath", "maintenanceExcel");
                    StringBuffer url = WebUtil.getRequest().getRequestURL();
                    String fileName = "import_Error(" + "导入错误信息" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
                    webPath = "https://file.wiscloud.online/maintenanceDeviceImport/"+fileName;
                    ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
                    // 一次性写出内容，使用默认样式
                    writer.write(errorList);
                    writer.setColumnWidth(1, 30);
                    writer.setColumnWidth(2, 30);
                    writer.setColumnWidth(3, 30);
                    writer.renameSheet("导入错误信息");
                    // 关闭writer，释放内存
                    writer.close();
                }
            }
        }catch (Exception e) {
            throw e;
        }finally {
            closeSession(session);
        }
        excelList.removeAll(removeList);
        // 拼装返回结果
        JSONObject result = new JSONObject();
        result.put("ErrorNum", errorList.size());
        result.put("SuccesNum", excelList.size());
        result.put("webPath", webPath);
        return RespEntity.success(result);
    }
    /**
     * @Author YangYu
     * @Description 单位导入模板下载
     * @Date Created in 15:33 2022/10/12
     * @Param [params]
     */

    public ResponseEntity<byte[]> getBusinessTemplate(Map<String, Object> params) throws Exception {
        JSONObject obj = new JSONObject();
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("企业名称", "");
        map.put("企业代码", "");
        map.put("经度", "");
        map.put("纬度", "");
        map.put("详细地址", "");
        map.put("机构ID", "");
        map.put("消防第一负责人", "");
        map.put("消防第一负责人电话", "");
        map.put("消防安全负责人", "");
        map.put("消防安全负责人电话", "");
        map.put("消防安全管理人", "");
        map.put("消防安全管理人电话", "");
        Iterable<?> rowData = map.keySet();
        fieldList.add(map);
        //机构list
        List<Map<String, String>> orgList = new ArrayList<>();
        Map<String, String> orgmap = new LinkedHashMap<>();
        orgmap.put("机构名称", "");
        orgmap.put("机构ID", "");
        orgList.add(orgmap);
        List<Map<String, String>> dataList = (List<Map<String, String>>) makeDataForJSON(obj, "systemsetup", "config", "getOrgList", "systemsetup");
        orgList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String fileName = "import_part(" + "企业导入" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.merge(11, "注释：\r\n1.必填项:企业名称、经度、纬度、详细地址、机构ID、消防第一负责人、消防第一负责人电话、消防安全负责人、消防安全负责人电话、消防安全管理人、消防安全管理人电话；\r\n"+"2.经纬度:从平台一企一档获取复制粘贴；\r\n" +"3.其他数据全部默认，如需更改导入完成后在平台进行修改；\r\n"+"4.机构ID数据来源:见工作表机构列表（机构列表中没有先去平台添加）；\r\n", false);
        writer.setRowHeight(0, 75);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 35);
        writer.setColumnWidth(6, 20);
        writer.setColumnWidth(7, 25);
        writer.setColumnWidth(8, 20);
        writer.setColumnWidth(9, 25);
        writer.setColumnWidth(10, 20);
        writer.setColumnWidth(11, 25);
        CellStyle cellStyle = writer.getOrCreateCellStyle(0, 0);
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setWrapText(true);
        Font font = writer.createFont();
        font.setColor(Font.COLOR_RED);
        cellStyle.setFont(font);
        writer.setCurrentRow(1);
        writer = writer.writeHeadRow(rowData);
        writer.setOnlyAlias(false);
        writer.write(fieldList);
        writer.renameSheet("导入");
        writer.flush();
        writer.setSheet("机构");
        font.setColor(Font.COLOR_NORMAL);
        writer.setCurrentRow(0);
        writer.write(orgList);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 40);
        // 关闭writer，释放内存
        writer.close();
        return downloadExcel(fileName);
    }

    /**
     * 显示控制装置历史数据记录导出
     * @param params
     * @return
     * @throws Exception
     */
    public RespEntity exportWaterColumnBoxDataLog(Map<String, Object> params) {

        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        map.put("number", "设备编号");
        map.put("waterLevel", "数据");
        map.put("dateTime", "发送时间");
        List<LinkedHashMap<String, String>> dataList = deviceAlarmLogMapper.exportWaterColumnBoxDataLog(params);
        fieldList.addAll(dataList);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        String fileName = "历史数据" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        String webPath = ConfigKit.getStr("path", "excel")+fileName;
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 20);
        writer.setHeaderAlias(map);
        writer.write(fieldList);
        writer.renameSheet("历史数据");
        // 关闭writer，释放内存
        writer.close();
        Map<String, Object> fileMap = new HashMap<>();
        fileMap.put("filePath", webPath);
        fileMap.put("fileName", fileName);
        return RespEntity.success(fileMap);
    }
}
